﻿#include "cadreroll.h"
#include "ui_cadreroll.h"
#include "timeeditdelegate.h"
#include <QSqlRecord>
#include <QSqlTableModel>
#include <QSqlQuery>
#include <QMessageBox>
#include "rollcadresearchresultdialog.h"
#include <QDebug>
#include <QTextDocument>
#include <QPrinter>
#include <QTextBlock>
#include <QFile>
#include <QFileDialog>

CadreRoll::CadreRoll(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::CadreRoll)
{
    ui->setupUi(this);
    rollModel = new QSqlQueryModel(this);
    initTableView();
}

CadreRoll::~CadreRoll()
{
    delete ui;
}

void CadreRoll::on_lockPushButton_clicked()
{
    QString text = ui->lockPushButton->text();
    if(text==QString::fromUtf8("锁定(F1)")){
        ui->lockPushButton->setText(QString::fromUtf8("编辑(F1)"));
        ui->addPushButton->setEnabled(false);
        ui->deletePushButton->setEnabled(false);
        ui->editPushButton->setEnabled(false);

    }else {
        ui->lockPushButton->setText(QString::fromUtf8("锁定(F1)"));
        ui->addPushButton->setEnabled(true);
        ui->deletePushButton->setEnabled(true);
        ui->editPushButton->setEnabled(true);
    }
}

void CadreRoll::on_addPushButton_clicked()
{
    flags="add";
    createDialog= new RollCreateDialog(this);
    createDialog->exec();
}
// ids 查询出来的rollid列表；selectid 编辑名册返回的rollid
void CadreRoll::initTableView(QStringList ids,int selectid)
{
    QString sql = " SELECT `RollId`, `RollDate`, `RollName` FROM Roll Where RollType='1' ";
    if(ids.size()> 0){
        sql = sql+ " and ";
        for(int i=0;i<ids.size();i++){
            if(i!=ids.size()-1)
                sql = sql+ QString("RollId=%1 or ").arg(ids[i]);
            else
                sql = sql+ QString("RollId=%1").arg(ids[i]);
        }
    }
    rollModel->setQuery(sql);
    rollModel->setHeaderData(1, Qt::Horizontal, QString::fromUtf8("日期"));
    rollModel->setHeaderData(2, Qt::Horizontal, QString::fromUtf8("名册名称"));
    int count = rollModel->rowCount();
    TimeEditDelegate *rolldate = new TimeEditDelegate();
    ui->rollTableView->setItemDelegateForColumn(1,rolldate);
    ui->rollTableView->setModel(rollModel);
    ui->rollTableView->setColumnWidth(1,160);
    ui->rollTableView->setColumnHidden(0,true);
    lastIndex = count-1;
    QModelIndex clickindex;
    if(selectid==0){
//        currentRoll=rollModel->record(lastIndex).value("RollId").toInt();
//        ui->rollTableView->selectRow(lastIndex);
        clickindex = rollModel->index(lastIndex,0);
    }else{
        int cindex;
        for(int i=0;i<count;i++){
            if(rollModel->record(i).value("RollId").toInt()==selectid)
                cindex = i;
        }
//        ui->rollTableView->selectRow(cindex);
//        currentRoll = selectid;
        clickindex = rollModel->index(cindex,0);

    }
    on_rollTableView_clicked(clickindex);
    ui->rollNumLineEdit->setText(QString::number(count));
}
void CadreRoll::initCadreRollTableView()
{
    QString sqlquery = QString::fromUtf8("SELECT `CadreName`, `UsedName`, cc.`CredType`, ci.`IDNum`, "
                         "`Birth`, `JoinWorkTime`, `Sex`, `Health`, nationc.`Nation`, "
                         "`NativePlace`, `BirthPlace`, `GrowPlace`, politicc.`Politic`, "
                         "`PartyTime`,`DemoParty`, `RetireChange`, `Speciality`, "
                         "msc.`ManageStatus`, `IdenCate`, `ThreeOne`, `Phone`, "
                         "`SubstratumWork`, uc.unitname, rc.`RankName`, `RankTime`, "
                         "`RankSalary`, `Photo`, p1.`PostName`, pmin.minposttime  "
                         "FROM ZZB.CadreInfo ci "
                         "inner join ZZB.CadreRollRelation ccr on ccr.`IDNum`=ci.`IDNum` "
                         "left join ZZB.CredTypeCode cc on ci.`CredTypeID`= cc.`CredTypeID` "
                         "left join ZZB.NationCode nationc on nationc.`NationID`=ci.`NationID` "
                         "left join ZZB.PoliticCode politicc on politicc.`PoliticID`=ci.`PoliticID` "
                         "left join ZZB.ManageStatusCode msc on msc.`ManageStatusID`=ci.`ManageStatusID` "
                         "left join ZZB.unit uc on uc.`UnitID`=ci.`UnitID` "
                         "left join ZZB.RankCode rc on rc.`RankID`=ci.`RankID` "
                         "left join ZZB.Post p  on p.`IDNum` = ci.`IDNum` "
                         "left join (select GROUP_CONCAT(`PostName`) as postname, "
                                "`IDNum` as `pIDNum` from Post where QualifyType='0' group by `IDNum`) p1 "
                                "on p1.pIDNum=p.`IDNum` "
                         "left join (select min(`PostTime`) as minposttime,`IDNum` "
                                "from Post group by `IDNum`) pmin on pmin.`IDNum`=p.`IDNum` "
                         "where RollId = '%1'").arg(currentRoll);
    cadrerollMode = new ResultTableModel(this);
    cadrerollMode->setQuery(sqlquery);

    int cunitname = cadrerollMode->record().indexOf("unitname");
    int cpostname = cadrerollMode->record().indexOf("PostName");
    int cminposttime = cadrerollMode->record().indexOf("minposttime");
    int crankname = cadrerollMode->record().indexOf("RankName");
    int cranktime = cadrerollMode->record().indexOf("RankTime");

    cadrerollMode->setHeaderData(0, Qt::Horizontal, QString::fromUtf8("姓名"));
    cadrerollMode->setHeaderData(3, Qt::Horizontal, QString::fromUtf8("证件号码"));
    cadrerollMode->setHeaderData(4, Qt::Horizontal, QString::fromUtf8("出生日期"));
    cadrerollMode->setHeaderData(6, Qt::Horizontal, QString::fromUtf8("性别"));
    cadrerollMode->setHeaderData(cunitname, Qt::Horizontal, QString::fromUtf8("单位"));
    cadrerollMode->setHeaderData(cpostname, Qt::Horizontal, QString::fromUtf8("职务"));
    cadrerollMode->setHeaderData(cminposttime, Qt::Horizontal, QString::fromUtf8("现职时间"));
    cadrerollMode->setHeaderData(crankname, Qt::Horizontal, QString::fromUtf8("级别"));
    cadrerollMode->setHeaderData(cranktime, Qt::Horizontal, QString::fromUtf8("级别时间"));
    int count=cadrerollMode->columnCount();
    ui->cadreRollTableView->setModel(cadrerollMode);
    QHash<int,QString> showidlist = uniqueCadre();

    for(int i=0;i<count;i++){
        if(i==0|| i==3 || i==4 || i==6 || i==cunitname || i==cpostname
                || i==cminposttime || i==crankname || i==cranktime){
        }else{
            ui->cadreRollTableView->setColumnHidden(i,true);
        }
    }
    ui->cadreRollTableView->horizontalHeader()->setVisible(true);

    TimeEditDelegate *birthtime = new TimeEditDelegate();
    ui->cadreRollTableView->setItemDelegateForColumn(4,birthtime);
    TimeEditDelegate *minposttime = new TimeEditDelegate();
    ui->cadreRollTableView->setItemDelegateForColumn(cminposttime,minposttime);
    TimeEditDelegate *ranktime = new TimeEditDelegate();
    ui->cadreRollTableView->setItemDelegateForColumn(cranktime,ranktime);

    cadrerollMode->chash["Sex"]=6; //性别的列数

    ui->cadreRollTableView->setColumnWidth(cpostname,300);
    ui->cadreRollTableView->show();
    ui->cadreNumLineEdit->setText(QString::number(showidlist.size()));
}
// 所有相同IDNum的就显示一列
QHash<int,QString> CadreRoll::uniqueCadre()
{
    QHash<int,QString> idlist,newidlist;
    QList<int> showids;

    int rowcount = cadrerollMode->rowCount();
    int idcolumn = cadrerollMode->record().indexOf("IDNum");
    for(int i=0;i<rowcount;i++){
        idlist[i]=cadrerollMode->data(cadrerollMode->index(i,idcolumn)).toString();
    }
    foreach(QString value,idlist.values().toSet() ){
        showids << idlist.key(value); // 只返回一个key
        newidlist[idlist.key(value)]=value;
    }

    for(int i=0;i<rowcount;i++){

        ui->cadreRollTableView->setRowHidden(i,false);// 特别重要，要是不加此句，清除查询条件后，再按搜索table不会更新,或者显示不全

        if(!showids.contains(i)){
            ui->cadreRollTableView->setRowHidden(i,true);
        }

    }
    return newidlist;
}
void CadreRoll::on_rollTableView_clicked(const QModelIndex &index)
{
    QSqlRecord rowData = rollModel->record(index.row());
    currentRoll = rowData.value("RollId").toInt();
    ui->rollTableView->selectRow(index.row());
    initCadreRollTableView();

}

void CadreRoll::on_deletePushButton_clicked()
{
    QSqlQuery query = rollModel->query();
    QString sql = QString::fromUtf8("delete from Roll where RollId='%1'").arg(currentRoll);
    if(query.exec(sql)) {
        initTableView();
        initCadreRollTableView();
    }else {
        QMessageBox::information(this,trUtf8("操作提示"),
            trUtf8("操作失败"),QMessageBox::Yes);
    }
}

void CadreRoll::on_editPushButton_clicked()
{
    flags="edit";
    editDialog= new RollEditDialog(this);
    editDialog->exec();
}

void CadreRoll::on_searchPushButton_clicked()
{
    QString rollname = ui->rollNameLineEdit->text();
    QString cadrename = ui->cadrenameLineEdit->text();
    QString unit = ui->unitNameLineEdit->text();
    QDate startdate = ui->startDateEdit->date();
    QDate enddate = ui->endDateEdit->date();

    QString sqlquery =QString( "SELECT roll.`RollId`, `RollDate`, `RollName` "
                         "FROM ZZB.Roll roll  "
                         "inner join ZZB.CadreRollRelation ccr on roll.`RollID`= ccr.`RollID` "
                         "inner join ZZB.CadreInfo ci on ccr.`IDNum`=ci.`IDNum` "
                         "left join ZZB.unit unit on unit.`UnitID`=ci.`UnitID` "
                         "where `RollDate` between :start and :end ");
    if(!rollname.isEmpty()){
        sqlquery = sqlquery + QString(" and RollName like '%%1%'").arg(rollname);
    }
    if(!unit.isEmpty()){
        sqlquery = sqlquery + QString(" and UnitName like '%%1%'").arg(unit);
    }
    if(!cadrename.isEmpty()){
        sqlquery = sqlquery + QString(" and CadreName like '%%1%'").arg(cadrename);
    }
    QSqlQueryModel *model = new QSqlQueryModel();
    QSqlQuery query = model->query();
    query.prepare(sqlquery);
    query.bindValue(":start",startdate);
    query.bindValue(":end",enddate);
    query.exec();
    model->setQuery(query);
    qDebug()<<sqlquery;
    QStringList ids;
    for (int i=0;i<model->rowCount(); i++){
        ids << model->record(i).value("RollId").toString();
    }
    QSet<QString> idset =  ids.toSet();
    ids.clear();
    ids = idset.toList();
    initTableView(ids);
}
QString CadreRoll::saveHtmlToPDF()
{
    QHash<int,QString> showidlist = uniqueCadre();
    int count = showidlist.size();
    QString html = "";
    html += "<html>";
    html += "<head>";
    html += "<title>"+QString::fromUtf8("干部名册导出PDF文档")+"</title>";
    html += "</head>";
    html += "<body>";
    html += "<h1 align=\"center\">"+QString::fromUtf8("干部名册")+"</h1>";
    html += "<span>"
            "<label align=\"right\">"+ QDate::currentDate().toString("yyyy-MM-dd") +"</label>"
            "&nbsp;&nbsp;&nbsp;"
            "<label>"+QString::fromUtf8("共")+QString::number(count)+QString::fromUtf8("人")+"</label></span>";
    html += "<table width=\"100%\" border=\"1\" cellspacing=\"1\" cellpadding=\"4\" align=\"center\">";
    html += "<tr >";
    html += "<th  align=\"center\" valign=\"middle\">"+QString::fromUtf8("序号")+"</th>";
    html += "<th  align=\"center\" valign=\"middle\">"+QString::fromUtf8("姓名")+"</th>";
    html += "<th  align=\"center\" valign=\"middle\">"+QString::fromUtf8("现任职务")+"</th>";
    html += "<th  align=\"center\" valign=\"middle\">"+QString::fromUtf8("任职时间")+"</th>";
    html += "<th  align=\"center\" valign=\"middle\">"+QString::fromUtf8("级别")+"</th>";
    html += "<th  align=\"center\" valign=\"middle\">"+QString::fromUtf8("同级时间")+"</th>";
    html += "<th  align=\"center\" valign=\"middle\">"+QString::fromUtf8("性别")+"</th>";
    html += "<th  align=\"center\" valign=\"middle\">"+QString::fromUtf8("出生年月")+"</th>";
//    html += "<th colspan=\"2\" rowspan=\"1\" align=\"center\" valign=\"middle\">"+QString::fromUtf8("学历(学位)及毕业学校、专业")+"</th>";
//    html += "<th  align=\"center\" valign=\"middle\">"+QString::fromUtf8("职称")+"</th>";
    html += "<th  align=\"center\" valign=\"middle\">"+QString::fromUtf8("籍贯")+"</th>";
    html += "<th  align=\"center\" valign=\"middle\">"+QString::fromUtf8("出生地")+"</th>";
    html += "<th  align=\"center\" valign=\"middle\">"+QString::fromUtf8("工作时间")+"</th>";
    html += "<th  align=\"center\" valign=\"middle\">"+QString::fromUtf8("入党时间")+"</th>";
    html += "<th  align=\"center\" valign=\"middle\">"+QString::fromUtf8("备注")+"</th>";
    html += "</tr>";
    for(int i=0;i<cadrerollMode->rowCount();i++)
    {
        if(showidlist.keys().contains(i)){
            QString cname = cadrerollMode->record(i).value("CadreName").toString();
            QString cpostname = cadrerollMode->record(i).value("PostName").toString();
            QString cminposttime = cadrerollMode->record(i).value("minposttime").toString();
            QString crankname = cadrerollMode->record(i).value("RankName").toString();
            QString cranktime = cadrerollMode->record(i).value("RankTime").toString();
            QString csex = cadrerollMode->record(i).value("Sex").toString();
            if(csex=="1") csex=QString::fromUtf8("男");
            if(csex=="0") csex=QString::fromUtf8("女");
            QString cbirth = cadrerollMode->record(i).value("Birth").toString();
            QString cnativeplace = cadrerollMode->record(i).value("NativePlace").toString();
            QString cbirthplace = cadrerollMode->record(i).value("BirthPlace").toString();
            QString cjoinworktime = cadrerollMode->record(i).value("JoinWorkTime").toString();
            QString cpartytime = cadrerollMode->record(i).value("PartyTime").toString();

            html += "<tr><td align=\"center\" valign=\"middle\">"+QString::number(i+1)+"</td>"
                    "<td align=\"center\" valign=\"middle\">"+ cname+"</td>"
                    "<td align=\"center\" valign=\"middle\">"+ cpostname +"</td>"
                    "<td align=\"center\" valign=\"middle\">"+ cminposttime+"</td>"
                    "<td align=\"center\" valign=\"middle\">"+ crankname +"</td>"
                    "<td align=\"center\" valign=\"middle\">"+ cranktime+" </td>"
                    "<td align=\"center\" valign=\"middle\">"+ csex +"</td>"
                    "<td align=\"center\" valign=\"middle\">"+ cbirth +"</td>"
                    "<td align=\"center\" valign=\"middle\">"+ cnativeplace+"</td>"
                    "<td align=\"center\" valign=\"middle\">"+ cbirthplace +"</td>"
                    "<td align=\"center\" valign=\"middle\">"+ cjoinworktime+" </td>"
                    "<td align=\"center\" valign=\"middle\">"+ cpartytime +"</td>"
                    "<td align=\"center\" valign=\"middle\">&nbsp;&nbsp;&nbsp;</td></tr>";
        }

    }
    html += "</table>";
    html += "</body>";
    html += "</html>";
    return html;
}

void CadreRoll::on_expertPushButton_clicked()
{
    QString pdfname = QFileDialog::getSaveFileName( this, "Save", "", "*.pdf" );
    QFile file(pdfname);
    if( !file.open(QFile::WriteOnly | QFile::Text) )
    {
        return;
    }
    QPrinter printer;
    printer.setOutputFormat(QPrinter::PdfFormat);
    printer.setOutputFileName(pdfname);
    QTextDocument document;
    QString html = saveHtmlToPDF();
    document.setHtml(html);
    document.print(&printer);
    document.end();
}
